package com.autonavi.yunda.yunji.job.executor.service;

import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.UUID;

import static com.autonavi.yunda.yunji.common.constant.CommonConstant.MDC_TRACE_ID;

/**
 * @author cizhong.wcs
 * @date 2022/6/21 14:50
 */
@Slf4j
@Component
@EnableScheduling
public class ExecutorScheduledService {
    @Resource
    private XxlJobSpringExecutor xxlJobSpringExecutor;

    /**
     * 刷新 script 和 jobHandler
     */
    @Scheduled(cron = "0 0/5 * * * *")
    public void checkAndRefreshExecutorInfo() {
        MDC.put(MDC_TRACE_ID, DigestUtils.md5DigestAsHex(UUID.randomUUID().toString().getBytes()));
        log.warn("checkAndRefreshScriptClassManager start");
        try {
            xxlJobSpringExecutor.initAndRefreshEngineJobHandler();
        } catch (Exception e) {
            log.error("checkAndRefreshScriptClassManager error", e);
        } finally {
            log.warn("checkAndRefreshScriptClassManager end");
            MDC.remove(MDC_TRACE_ID);
        }
    }
}
